﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;

namespace Maticsoft.Common
{
    public class IPHelper
    {
        /// <summary>
        /// 获取客户端的IP
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }

            if (null == result || result == String.Empty)
            {
                result = HttpContext.Current.Request.UserHostAddress;
            }
            return result;
        }

        /// <summary>
        /// 根据ip获取地址
        /// </summary>
        /// <returns></returns>
        public static string GetWhereByIP()
        {
            string result = "";
            string url = "http://whois.pconline.com.cn/ip.jsp?ip=" + GetClientIP();
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "GET";
                request.KeepAlive = false;
                request.Timeout = 5000;
                HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                Stream responseStream = response.GetResponseStream();
                StreamReader sdr = new StreamReader(responseStream, Encoding.Default);
                result = sdr.ReadToEnd();
            }
            catch (Exception ex)
            {
                result = "未知";
                LogManager.WriteLog(ex.Message);
            }
            return result;
        }

    }
}
